module app.service.paybillservice;

import app.model;
import hunt;
import app.model.db;
import app.service.base;
import app.helper.snowflake;


class PayBillService{
	mixin ServiceUtility!("pay_bill", PayBillService);
	
	string insertData(PayBill bill, Connection * db = DB())
	{
		import std.format;
		import std.conv;
		
		auto id = snowflake.generate();
		
		string sqlstr = format("INSERT INTO public.pay_bill(id, out_trade_no,  amount, channel, appid, create_time,subject, body, status, passback_params,notify_url)VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);",
			id,
			db.escapeLiteral(bill.outTradeNo),
			bill.amount,
			db.escapeLiteral(bill.channel),
			db.escapeLiteral(bill.appid),
			bill.createTime,
			db.escapeLiteral(bill.subject),
			db.escapeLiteral(bill.body_),
			bill.status,
			db.escapeLiteral(bill.passbackParams),
			db.escapeLiteral(bill.notifyUrl)
			);
		trace("sql is : ", sqlstr);
		db.exec(sqlstr);
		return to!string(id);
	}
	
	PayBill getByWhere(string[string] whereCondition)
	{
		import std.array, std.conv;
		Appender!string sql = appender!string();
		sql.put("SELECT * ");
		sql.put(" FROM \"");
		sql.put(getTableName());
		sql.put("\" ");
		
		string[] wheres;
		
		foreach(i, col; whereCondition) 
		{
			wheres ~= "\"" ~i~ "\"=" ~ DB().escapeLiteral(col);
		}
		if(wheres.length != 0 )
		{
			sql.put(" WHERE ");
			sql.put(wheres.join(" AND "));
		}
		
		trace("sql:", sql.data);
		auto result = DB().exec(sql.data);
		if(result.rows()==0)
		{
			return null;
		}
		
		
		auto row = result.front;
		import std.typecons;
		Nullable!string tmp ;
		PayBill bill = new PayBill();
		bill.id = to!ulong(row["id"].as!string().get());
		bill.outTradeNo = row["out_trade_no"].as!string().get();
		tmp = row["trade_no"].as!string();
		bill.tradeNo = tmp.isNull ? "" : tmp.get();
		tmp = row["channel"].as!string();
		bill.channel = tmp.isNull ? "" : tmp.get();
		tmp = row["appid"].as!string();
		bill.appid = tmp.isNull ? "" : tmp.get();
		tmp = row["notify_url"].as!string();
		bill.notifyUrl = tmp.isNull ? "" : tmp.get();
		tmp = row["subject"].as!string();
		bill.subject = tmp.isNull ? "" : tmp.get();
		tmp = row["body"].as!string();
		bill.body_ = tmp.isNull ? "" : tmp.get();
		tmp = row["passback_params"].as!string();
		bill.passbackParams = tmp.isNull ? "" : tmp.get();
		tmp = row["amount"].as!string();
		bill.amount = to!int(tmp.isNull ? "0" : tmp.get());
		tmp = row["create_time"].as!string();
		bill.createTime = to!ulong(tmp.isNull ? "0" : tmp.get());
		tmp = row["payment_time"].as!string();
		bill.paymentTime = to!ulong(tmp.isNull ? "0" : tmp.get());
		tmp = row["refund_time"].as!string();
		bill.refundTime = to!ulong(tmp.isNull ? "0" : tmp.get());
		tmp = row["status"].as!string();
		bill.status = to!short(tmp.isNull ? "0" : tmp.get());
		tmp = row["notify_success_time"].as!string();
		bill.notifySuccessTime = to!short(tmp.isNull ? "0" : tmp.get());
		return bill;
	}
}